<template>
  <main-card-admin title="授权管理" :tabs="getTabs()" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #screen-space>
      <a-row :align="'middle'" justify="space-between">
        <a-col class="mr-24">
          <condition-input :condition="condition" @search="onSearch" />
        </a-col>
      </a-row>
    </template>
    <a-table
      :style="{ width: '100%' }"
      :columns="tableColumns"
      :data-source="logList"
      :loading="loading"
      :pagination="false"
      :custom-row="(r:any) => ({ onClick: () => previewClient(r) })"
      class="header-right-angle admin-table"
      @change="onTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'operation'">
          <span v-auth="'auth-manage-down-license'" class="download-btn" @click.stop="handleDownLoad(record)">
            <i class="iconfont icon-download-2-line"></i>
          </span>
        </template>
      </template>
    </a-table>
    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getListData" />
  </main-card-admin>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { debounce } from 'g6-fn'
  import { ref } from 'vue'
  import { useRouter } from 'vue-router'

  import ConditionInput from '@/components/ConditionInput/index.vue'
  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import manualMessage from '@/components/ManualMessage'
  import useList from '@/hooks/use-list'
  import { authApi, fetchDownload } from '@/services/api'
  import { filterTableColumns } from '@/utils/ant-component'

  import { getTabs } from '../common'
  import { DetailInfo } from '../types/license'

  interface PageForm {
    name: string
    username: string
    number: string
    customerId: string
    licenseId: string
    columns: 'updateTime' | 'createTime'
    order: 'desc' | 'asc'
  }

  const router = useRouter()

  const condition = [
    { name: 'License ID', key: 'licenseId' },
    { name: '用户名称', key: 'username' },
    { name: '应用编号', key: 'number' },
    { name: '应用名称', key: 'name' }
  ]
  const onSearch = (obj: any) => {
    getListData({ offset: 1, ...obj })
  }

  const {
    pageForm,
    dataList: logList,
    getDataList: getListData,
    loading
  } = useList<PageForm, DetailInfo>(authApi.licenseList, {
    username: '',
    name: '',
    number: '',
    customerId: '',
    licenseId: '',
    columns: 'updateTime',
    order: 'desc'
  })
  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: 'License ID',
        dataIndex: 'licenseId',
        width: 180
      },
      {
        title: '用户名称',
        dataIndex: 'username',
        width: 140
      },
      {
        title: '应用编号',
        dataIndex: 'number',
        width: 180
      },
      {
        title: '应用名称',
        dataIndex: 'name'
      },
      {
        title: '应用更新时间',
        dataIndex: 'updateTime',
        isSort: true,
        width: 180
      },
      {
        title: '应用创建时间',
        dataIndex: 'createTime',
        isSort: true,
        width: 180
      },
      {
        title: '',
        dataIndex: 'operation',
        width: 80,
        align: 'right'
      }
    ])
  )
  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    let columns = sorter.field
    let order = sorter.order === 'ascend' ? 'asc' : ('desc' as any)
    if (!sorter.order) {
      columns = 'updateTime'
      sorter.order = 'desc'
    }
    getListData({ offset: 1, order, columns })
  }

  const previewClient = (item: any) => {
    router.push({
      path: '/auth-manage/license/detail',
      query: {
        id: item.id
      }
    })
  }

  // 下载
  const handleDownLoad = debounce(async (row: Record<string, any>): Promise<void> => {
    manualMessage.loading('数据准备中,请耐心等待...', 0)
    try {
      const { data } = await authApi.downLicense(row.id)(
        {},
        {
          isResponseAll: true,
          timeout: 300000 //设置超时时长5min
        }
      )
      await fetchDownload(data.data.fileUrl, data.data.fileName)
      manualMessage.destroy()
      await message.success({ content: '文件下载成功', key: 'downloading', duration: 2 })
      console.log('下载成功')
    } catch (error) {
      console.log('下载失败', error)
      manualMessage.destroy()
      message.error({ content: '文件下载失败', key: 'downloading', duration: 2 })
    }
  }, 500)

  getListData()
</script>

<style lang="less" scoped>
  .ant-btn-link:hover {
    background-color: red;
  }

  .download-btn {
    padding: 4px;
    color: @secondary1;
    border-radius: 6px;
    cursor: pointer;

    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
  }
</style>
